<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isLook ? '查看' : form.pa_id ? '编辑' : '添加'" class="full"
    v-model="visible" align-center width="1300px" :z-index="2000" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :disabled="isLook" :label-width="100" class="h-full">
      <div class="flex flex-col h-full">
        <div>
          <div class="v-title mb-3">基础信息</div>
          <div class="grid grid-cols-4 gap-x-3">
            <el-form-item label="特采单号">
              <el-input v-model="form.psp_no" disabled />
            </el-form-item>
            <el-form-item label="申请人员">
              <el-input v-model="form.create_user" disabled />
            </el-form-item>
            <el-form-item label="申请时间">
              <el-input v-model="form.apply_time" disabled />
            </el-form-item>
            <el-form-item label="申请部门">
              <VCascader v-model="form.apply_depart_id" placeholder="申请部门" type="1" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="计划类型" prop="plan_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.plan_type" :options="options.plan_type" placeholder="请输入" class="w-full" />
            </el-form-item>
            <el-form-item label="备货类型" prop="demand_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.demand_type" :options="options.demand_type" placeholder="请输入" class="w-full" />
            </el-form-item>
            <el-form-item label="审核状态">
              <VSelect v-model="form.audit_status" placeholder="" :options="options.audit_status" disabled filterable
                clearable class="w-full" />
            </el-form-item>
            <el-form-item label="飞书审核">
              <div class="flex items-center gap-3 mb-4">
                <el-switch v-model="form.is_feishu_audit" inline-prompt active-text="是" inactive-text="否"
                  :active-value="2" :inactive-value="1" @change="(form.files_code = []) && (form.files = [])" />
                <div class="text-green-600 text-xs">提示：启用后只能在飞书审核</div>
              </div>
            </el-form-item>
          </div>
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"></el-input>
          </el-form-item>
          <template v-if="form.is_feishu_audit">
            <VUpload v-if="form.is_feishu_audit === 2" v-model="form.files_code" multiple :params="{ is_origin: 2 }"
              :types="['xls', 'xlsx', 'png', 'jpg', 'jpeg', 'pdf']" title="附件" class="mb-5" />
            <VUpload v-else v-model="form.files" title="附件" multiple :params="{ is_origin: 2 }"
              :types="['xls', 'xlsx', 'png', 'jpg', 'jpeg', 'pdf']" class="mb-5" />
          </template>
          <div class="v-title mt-4">产品信息</div>
          <div class="my-3 flex items-center">
            <el-button type="primary" @click="goodsRef.open">添加sku</el-button>
            <el-button @click="batchRemove">批量删除</el-button>
            <VImport :tableRef="tableRef" importUrl="/v1/product/product-special-purchase/import-sku"
              downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/product_special_sku_template.xlsx"
              class="ml-auto" @success="goodsChange" />
          </div>
        </div>
        <div class="flex-1">
          <vxe-table ref="tableRef" :data="form.skus" height="auto">
            <vxe-column type="checkbox" :width="40" fixed="left"></vxe-column>
            <vxe-column title="图片" :min-width="80">
              <template #default="{ row }">
                <div class="flex items-center p-1">
                  <VImage :src="row.main_img"></VImage>
                </div>
              </template>
            </vxe-column>
            <vxe-column :min-width="120">
              <template #header>
                <div>sku</div>
                <div>产品状态</div>
              </template>
              <template #default="{ row }">
                {{ row.sku }}
                <div>{{ row.status }}</div>
              </template>
            </vxe-column>
            <vxe-column title="产品名称" field="sku_cn_title" :min-width="200">
              <template #default="{ row }">
                <VText :value="row.sku_cn_title" :line="3" />
              </template>
            </vxe-column>
            <vxe-column title="产品分类" :min-width="120">
              <template #default="{ row }">
                <VText :value="row.attribute_name" />
              </template>
            </vxe-column>
            <vxe-column field="is_invoice" :min-width="150">
              <template #header>
                供应商
                <div>是否开票</div>
              </template>
              <template #default="{ row }">
                <VText :value="row.supplier_name" />
                <VText :value="row.is_invoice_name" />
              </template>
            </vxe-column>
            <vxe-column :min-width="140">
              <template #header>
                国家
                <div>目的仓</div>
              </template>
              <template #default="{ row }">
                <div class="p-1">
                  <VSelect v-model="row.country_code" placeholder="请选择" :options="options.country" select filterable clearable
                    class="w-full" :disabled="isLook" @change="({ option }) => (row.country_name = option.label)" />
                  <VSelect v-model="row.warehouse_id" placeholder="请选择" type="warehouse" filterable clearable
                    class="w-full mt-1" :disabled="isLook"
                    @change="({ option }) => (row.warehouse_name = option.label)" />
                </div>
              </template>
            </vxe-column>
            <vxe-column title="采购/开发" :min-width="140">
              <template #header>
                采购
                <div>开发</div>
              </template>
              <template #default="{ row }">
                <div>{{ row.purchaser_name || row.purchase_user }}</div>
                <div>{{ row.developer_name || row.develop_user }}</div>
              </template>
            </vxe-column>
            <vxe-column title="单价" :min-width="80">
              <template #default="{ row }">{{ row.unit_price }}</template>
            </vxe-column>
            <vxe-column title="* 需求数量" :min-width="120">
              <template #header>
                <span class="text-red-500">*</span> 需求数量
              </template>
              <template #default="{ row, rowIndex }">
                <el-form-item :prop="['skus', rowIndex, 'demand_num']" label=""
                  :rules="[{ required: true, message: '不能为空' }]">
                  <el-input-number v-model="row.demand_num" :controls="false" :min="0" :step="1" :precision="0"
                    :disabled="isLook" class="w-full" />
                </el-form-item>
              </template>
            </vxe-column>
            <vxe-column title="​需求总金额" :min-width="100">
              <template #default="{ row }">
                {{ XEUtils.toFixed(row.demand_num * row.unit_price, 2) }}
              </template>
            </vxe-column>
            <vxe-column title="起批量" :min-width="80">
              <template #default="{ row }">{{ row.min_order_quantity }}</template>
            </vxe-column>
            <vxe-column title="采购天数" :min-width="140">
              <template #default="{ row }">{{ row.purchase_day || row.delivery_date }}</template>
            </vxe-column>
            <vxe-column title="组合sku" :min-width="80">
              <template #default="{ row }">{{ ['', '否', '是'][row.is_combination] }}</template>
            </vxe-column>
            <vxe-column title="需求运营" :min-width="140">
              <template #default="{ row }">
                <VCascader v-model="row.demand_sale" placeholder="请选择" filterable clearable :disabled="isLook"
                  class="w-full" />
              </template>
            </vxe-column>
            <vxe-column title="特采原因" :min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.purchase_reason" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
                  :disabled="isLook" placeholder="特采原因"></el-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
    </el-form>
    <template #footer>
      <template v-if="isLook">
        <el-button @click="close">关 闭</el-button>
      </template>
      <template v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings.create2" @click="create(2)">保 存</el-button>
        <el-button type="primary" :loading="loadings.create1" @click="create(1)">提 交</el-button>
      </template>
    </template>
  </el-dialog>
  <Goods ref="goodsRef" @change="goodsChange" />
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import Goods from '@/components/Goods'
import VImport from '@/components/VImport'
import XEUtils from 'xe-utils'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const isLook = ref(false)
let loadings = reactive({})
const tableRef = ref()

const userInfo = computed(() => window.userInfo)

// 表单处理
const formRef = ref()
const form = ref({})

const batchRemove = () => {
  const selection = tableRef.value.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
  }
  form.value.skus = form.value.skus.filter(d => !selection.some(s => s.p_id === d.p_id))
}

const goodsChange = (val) => {
  const { skus } = form.value
  const checkeds = val.filter(d => !skus.some(s => s.p_id === d.p_id))
  form.value.skus.unshift(...checkeds)
}

// 打开弹窗
const open = async (id, look) => {
  isLook.value = look
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  visible.value = true
  // 编辑
  if (id) {
    const res = await api.detail({ psp_id: id })
    // const { psp_id, bank_name, bank_type } = res.data
    // form.value = { psp_id, bank_name, bank_type }
    form.value = res.data
  } else { //新增
    formRef?.value?.resetFields()
    form.value =
    {
      create_user: userInfo.value.user?.en_name,
      apply_time: XEUtils.toDateString(new Date(), 'yyyy-MM-dd'),
      apply_depart_id: userInfo.value.departments[0]?.department_id,
      apply_depart_name: userInfo.value.departments[0]?.name,
      plan_type: null,
      demand_type: null,
      is_feishu_audit: 1,
      skus: [],
      files_code: [],
      files: [],
    }
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (is_submit) => {
  const validator = await formRef?.value.validate()
  console.log('validator', validator)
  if (!validator) return
  loadings['create' + is_submit] = true
  form.value.is_submit = is_submit
  api[form.value.psp_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings['create' + is_submit] = false
  })
}

// 商品
const goodsRef = ref()

defineExpose({ open })
</script>